<template>
	<view>
		<view class="content">
			<u-form :model="password" ref="uForm">
				<u-form-item label="旧密码" prop="old" label-width="120"><u-input type="password" v-model="password.old" /></u-form-item>
				<u-form-item label="新密码" prop="now" label-width="120"><u-input type="password" v-model="password.now" /></u-form-item>
				<u-form-item label="再次输入" label-width="180" prop="reture"><u-input type="password" v-model="password.reture" /></u-form-item>
			</u-form>
		</view>
		<button class="CommentBtn" @click="set">确定修改</button>
			<u-toast ref="uToast" />
	</view>
</template>

<script>
	import { changepassword, getuserinfo } from '../../api/user.js'
	export default {
		data() {
			return {
				password: {
					old: '',
					now: '',
					reture: ''
				},
				rules: {
					now: [
						{
							required: 'true',
							message: '请输入密码',
							trigger: ['change', 'blur']
						},
						{
							min: 3,
							max: 9,
							message: '长度在3-9个字符之间',
							trigger: ['change', 'blur']
						}
					],
					now: [
						{
							required: 'true',
							message: '请输入密码',
							trigger: ['change', 'blur']
						},
						{
							min: 3,
							max: 9,
							message: '长度在3-9个字符之间',
							trigger: ['change', 'blur']
						}
					],
					reture: [
						{
							required: 'true',
							message: '请再次输入密码',
							trigger: ['change', 'blur']
						},
						{
							validator: (rule, value, callback) => {
								return (value === this.password.now);
							},
							message: '前后密码不一致',
							trigger: ['change', 'blur']
						}
					]
				}
			}
		},
		onReady() {
		  this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			// 修改密码
			set () {
				this.$refs.uForm.validate( async (valid) => {
					if (valid) {
						if (this.password.old == this.$store.state.userinfo.userPassword) {
							const params = {
								newPassword: this.password.now,
								userId: this.$store.state.userinfo.userId
							}
							const res = await changepassword(params)
							if (res.statusCode == 200) {
								this.$refs.uToast.show({
									title: '修改密码成功',
									type: 'success',
								})
								this.$store.dispatch('getUserInfo')
								uni.navigateBack({
									delta: 1
								})
							}
						} else {
							this.$refs.uToast.show({
								title: '旧密码错误',
								type: 'error',
							})
						}
					} else {
						this.$refs.uToast.show({
							title: '数据格式有误',
							type: 'error',
						})
					}
				
				})
			}
		}
	}
</script>

<style lang="less" scoped>
.content {
	background-color: #fff;
	margin-top: 24rpx;
	padding: 0 24rpx;
	}
</style>
